import type { Context } from 'elysia';
import { eq, desc, like, and, or, ne } from 'drizzle-orm';
import { db } from '../db';
import { users } from '../db/schema';
import { nanoid } from 'nanoid';
import bcrypt from 'bcrypt';
import { successResponse, errorResponse, ApiError, asyncHandler, Logger } from '../utils/response';
import { createPaginationMeta } from '../utils/pagination';
import { logUserOperation, logDatabaseOperation } from '../utils/systemLogger';

/**
 * 获取用户列表
 */
export const getUsers = asyncHandler(async ({ query }: Context) => {
  Logger.info('=== 用户API被调用 ===', { query });
  
  const {
    page = '1',
    pageSize = '10',
    keyword = '',
    role = '',
    status = ''
  } = query as any;

  const pageNum = parseInt(page);
  const limitNum = parseInt(pageSize);
  const offset = (pageNum - 1) * limitNum;

  // 构建查询条件
  const conditions = [];
  
  if (keyword) {
    conditions.push(
      or(
        like(users.username, `%${keyword}%`),
        like(users.email, `%${keyword}%`)
      )
    );
  }
  
  if (role && role !== 'all') {
    conditions.push(eq(users.role, role));
  }
  
  if (status && status !== 'all') {
    conditions.push(eq(users.status, status));
  }

  const whereClause = conditions.length > 0 ? and(...conditions) : undefined;

  // 获取总数
  const totalResult = await db.select({ count: users.id }).from(users).where(whereClause);
  const total = totalResult.length;

  // 获取用户列表
  const userList = await db
    .select({
      id: users.id,
      username: users.username,
      email: users.email,
      role: users.role,
      avatar: users.avatar,
      status: users.status,
      lastLogin: users.lastLoginAt,
      createdAt: users.createdAt,
      updatedAt: users.updatedAt
    })
    .from(users)
    .where(whereClause)
    .orderBy(desc(users.createdAt))
    .limit(limitNum)
    .offset(offset);

  const pagination = createPaginationMeta(total, pageNum, limitNum);

  Logger.info('获取用户列表', {
    total,
    page: pageNum,
    limit: limitNum,
    keyword,
    role,
    status
  });

  return successResponse({
    users: userList,
    total,
    pagination
  });
});

/**
 * 获取用户详情
 */
export const getUser = asyncHandler(async ({ params }: Context) => {
  const { id } = params as { id: string };

  const userResult = await db
    .select({
      id: users.id,
      username: users.username,
      email: users.email,
      role: users.role,
      avatar: users.avatar,
      status: users.status,
      lastLogin: users.lastLoginAt,
      createdAt: users.createdAt,
      updatedAt: users.updatedAt
    })
    .from(users)
    .where(eq(users.id, id))
    .limit(1);

  const user = userResult[0];
  if (!user) {
    throw ApiError.notFound('用户不存在');
  }

  Logger.info('获取用户详情', { userId: id });
  return successResponse(user);
});

/**
 * 创建用户
 */
export const createUser = asyncHandler(async ({ body, user }: Context) => {
  // 权限检查：只有管理员可以创建用户
  if (!user || user.role !== 'admin') {
    throw ApiError.forbidden('权限不足，只有管理员可以创建用户');
  }
  
  const { username, password, email, role = 'guest', status = 'active' } = body as any;

  if (!username || !password || !email) {
    throw ApiError.validation('用户名、密码和邮箱不能为空');
  }

  // 检查用户名是否已存在
  const existingUser = await db
    .select()
    .from(users)
    .where(eq(users.username, username))
    .limit(1);

  if (existingUser.length > 0) {
    throw ApiError.conflict('用户名已存在');
  }

  // 加密密码
  const hashedPassword = await bcrypt.hash(password, 10);

  // 创建用户
  const newUserData = {
    id: nanoid(),
    username,
    password: hashedPassword,
    email,
    role,
    status,
    avatar: '/public/uploads/default-avatar.png', // 设置默认头像
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString()
  };

  const [newUser] = await db.insert(users).values(newUserData).returning({
    id: users.id,
    username: users.username,
    email: users.email,
    role: users.role,
    avatar: users.avatar,
    status: users.status,
    createdAt: users.createdAt,
    updatedAt: users.updatedAt
  });

  // 记录系统日志
  await logUserOperation(
    newUser.id,
    username,
    'user',
    'create',
    `创建用户: ${username} (${email})`,
    { role, status }
  );

  Logger.info('创建用户成功', { userId: newUser.id, username });
  return successResponse(newUser, '用户创建成功');
});

/**
 * 更新用户
 */
export const updateUser = asyncHandler(async ({ params, body, user }: Context) => {
  // 权限检查：只有管理员可以更新用户
  if (!user || user.role !== 'admin') {
    throw ApiError.forbidden('权限不足，只有管理员可以更新用户');
  }
  
  const { id } = params as { id: string };
  const updateData = body as any;

  // 检查用户是否存在
  const existingUser = await db.select().from(users).where(eq(users.id, id)).limit(1);
  if (existingUser.length === 0) {
    throw ApiError.notFound('用户不存在');
  }

  // 如果更新用户名，检查是否冲突
  if (updateData.username) {
    const conflictUser = await db
      .select()
      .from(users)
      .where(
        and(
          eq(users.username, updateData.username),
          // 排除当前用户
          ne(users.id, id)
        )
      )
      .limit(1);

    if (conflictUser.length > 0) {
      throw ApiError.conflict('用户名已存在');
    }
  }

  // 如果更新密码，需要加密
  if (updateData.password) {
    updateData.password = await bcrypt.hash(updateData.password, 10);
  }

  // 更新时间戳
  updateData.updatedAt = new Date().toISOString();

  // 更新用户
  const [updatedUser] = await db
    .update(users)
    .set(updateData)
    .where(eq(users.id, id))
    .returning({
      id: users.id,
      username: users.username,
      email: users.email,
      role: users.role,
      avatar: users.avatar,
      status: users.status,
      lastLogin: users.lastLoginAt,
      createdAt: users.createdAt,
      updatedAt: users.updatedAt
    });

  // 记录系统日志
  await logUserOperation(
    id,
    existingUser[0].username,
    'user',
    'update',
    `更新用户信息: ${existingUser[0].username}`,
    { updatedFields: Object.keys(updateData).filter(key => key !== 'updatedAt') }
  );

  // 如果修改了密码，单独记录
  if (body.password) {
    await logUserOperation(
      id,
      existingUser[0].username,
      'user',
      'change_password',
      `用户修改密码: ${existingUser[0].username}`
    );
  }

  Logger.info('更新用户成功', { userId: id });
  return successResponse(updatedUser, '用户更新成功');
});

/**
 * 删除用户
 */
export const deleteUser = asyncHandler(async ({ params, user }: Context) => {
  // 权限检查：只有管理员可以删除用户
  if (!user || user.role !== 'admin') {
    throw ApiError.forbidden('权限不足，只有管理员可以删除用户');
  }
  
  const { id } = params as { id: string };

  // 检查用户是否存在
  const existingUser = await db.select().from(users).where(eq(users.id, id)).limit(1);
  if (existingUser.length === 0) {
    throw ApiError.notFound('用户不存在');
  }

  // 不允许删除管理员用户
  if (existingUser[0].role === 'admin') {
    throw ApiError.forbidden('不能删除管理员用户');
  }

  // 删除用户
  await db.delete(users).where(eq(users.id, id));

  // 记录系统日志
  await logUserOperation(
    id,
    existingUser[0].username,
    'user',
    'delete',
    `删除用户: ${existingUser[0].username}`,
    { deletedUser: { username: existingUser[0].username, role: existingUser[0].role } }
  );

  Logger.info('删除用户成功', { userId: id });
  return successResponse(null, '用户删除成功');
});

/**
 * 切换用户状态
 */
export const toggleUserStatus = asyncHandler(async ({ params, user }: Context) => {
  // 权限检查：只有管理员可以切换用户状态
  if (!user || user.role !== 'admin') {
    throw ApiError.forbidden('权限不足，只有管理员可以切换用户状态');
  }
  
  const { id } = params as { id: string };

  // 检查用户是否存在
  const existingUser = await db.select().from(users).where(eq(users.id, id)).limit(1);
  if (existingUser.length === 0) {
    throw ApiError.notFound('用户不存在');
  }

  const currentStatus = existingUser[0].status;
  const newStatus = currentStatus === 'active' ? 'inactive' : 'active';

  // 更新用户状态
  const [updatedUser] = await db
    .update(users)
    .set({ 
      status: newStatus,
      updatedAt: new Date().toISOString()
    })
    .where(eq(users.id, id))
    .returning({
      id: users.id,
      username: users.username,
      email: users.email,
      role: users.role,
      status: users.status,
      lastLogin: users.lastLoginAt,
      createdAt: users.createdAt,
      updatedAt: users.updatedAt
    });

  // 记录系统日志
  await logUserOperation(
    id,
    existingUser[0].username,
    'user',
    'toggle_status',
    `${newStatus === 'active' ? '激活' : '禁用'}用户: ${existingUser[0].username}`,
    { oldStatus: currentStatus, newStatus }
  );

  Logger.info('切换用户状态成功', { userId: id, newStatus });
  return successResponse(updatedUser, `用户已${newStatus === 'active' ? '激活' : '禁用'}`);
});